#增加保存数据功能
import os.path
import time


def calculate_bmr(gender, weight, height, age):
    if gender == "男":
        bmr = 13.7 * weight + 5.0 * height - 6.8 * age + 66
    elif gender == "女":
        bmr = 9.6 * weight + 1.8 * height - 4.7 * age + 655
    else:
        print("性别输入错误，请重新输入！")
        bmr = None
    return bmr


data_file = "bmr_data.txt"

if not os.path.exists(data_file):
    with open(data_file, 'w') as f:
        f.write("时间,性别,体重(kg),身高(cm),年龄,BMR\n")

while True:
    try:
        gender, weight_str, height_str, age_str = input(
            "请输入性别（男/女）、体重（公斤）、身高（厘米）和年龄[空格隔开]: ").split()
        weight = float(weight_str)
        height = float(height_str)
        age = int(age_str)
    except ValueError:
        print("输入有误，请重新输入！")
        continue

    bmr = calculate_bmr(gender, weight, height, age)
    if bmr is not None:
        print("BMR 数值为：{:.2f}".format(bmr))

        # 将计算结果写入历史记录文件
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        with open(data_file, 'a') as f:
            f.write("{},{},{},{},{},{}\n".format(now, gender, weight, height, age, bmr))

    y_or_n = input('是否退出程序(y/n)？')
    while y_or_n not in ['y', 'n']:
        print("输入有误，请重新输入！")
        y_or_n = input('是否退出程序(y/n)？')
    if y_or_n == 'y':
        save_data = input("是否需要保存历史记录 (y/n)？ ")
        if save_data == "y":
            print("历史记录已保存到文件 {} 中。".format(data_file))
        else:
            print("历史记录未保存。")
        break